package interceptors

import (
	"context"
	"fmt"

	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

func NewInterceptorImpl() *InterceptorImpl {
	return &InterceptorImpl{}
}

type InterceptorImpl struct {
}

// Req/Resp 拦截器
// username/password
func (i *InterceptorImpl) UnaryServerInterceptor(
	ctx context.Context,
	req any,
	info *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler,
) (
	resp any,
	err error,
) {
	// http BasicAuth:  Authentication: base64(username:password)
	// grpc 是http2的怎么获取 这些头信息
	// metadata
	// MD is a mapping from metadata keys to values. Users should use the following
	// two convenience functions New and Pairs to generate MD.
	// type MD map[string][]string
	// A Header represents the key-value pairs in an HTTP header.
	//
	// The keys should be in canonical form, as returned by
	// [CanonicalHeaderKey].
	// type Header map[string][]string
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, fmt.Errorf("get auth failed")
	}
	ul := md.Get("username")
	pl := md.Get("password")
	if len(ul) == 0 || len(pl) == 0 {
		return nil, fmt.Errorf("用户名或者密码需要传递")
	}
	// 逻辑判断
	if !(ul[0] == "admin" && pl[0] == "123456") {
		return nil, fmt.Errorf("用户名或者密码错误")
	}

	// 响应后的处理
	return handler(ctx, req)
}

// Stream 拦截器
// 同学们自己练习
func (i *InterceptorImpl) StreamServerInterceptor(
	srv any,
	ss grpc.ServerStream,
	info *grpc.StreamServerInfo,
	handler grpc.StreamHandler) error {
	//meta
	// 重上下文中获取认证信息
	md, ok := metadata.FromIncomingContext(ss.Context())
	fmt.Print(md, ok)

	// stram 和 用户关系
	return nil
}
